
library(mongolite)
library(ggplot2)
library(ggthemes)
library(wesanderson)

source("./parse_base.R", encoding = "UTF-8")

Args <- commandArgs()

USEDB <- Args[6]
thedate <- Args[7]
host <- Args[8]
base_path <- Args[9]
export_png <- Args[10]

width_1 <- 1920
height_1 <- 1080

if (is.na(thedate)) thedate="20171009"
if (is.na(USEDB)) USEDB=TRUE
if (is.na(host)) host="localhost"
if (is.na(base_path)) base_path="D:/data/proj/DemoLang/R"
if (is.na(export_png)) export_png=TRUE

cat("The data ", thedate, ", mongo ip ", host, "\n")

#code：代码
#name:名称
#changepercent:涨跌幅
#trade:现价
#open:开盘价
#high:最高价
#low:最低价
#settlement:昨日收盘价
#volume:成交量
#turnoverratio:换手率
#amount:成交量
#per:市盈率
#pb:市净率
#mktcap:总市值
#nmc:流通市值

hs300 <- get_data("hs300", USEDB)
if (length(hs300) > 0) hs300 <- hs300[order(-hs300$weight),]

zz500s <- get_data("zz500s", USEDB)
if (length(zz500s) > 0) zz500s <- zz500s[order(-zz500s$weight),]

sz50s <- get_data("sz50s", USEDB)

#code,代码
#name,名称
#industry,所属行业
#area,地区
#pe,市盈率
#outstanding,流通股本(亿)
#totals,总股本(亿)
#totalAssets,总资产(万)
#liquidAssets,流动资产
#fixedAssets,固定资产
#reserved,公积金
#reservedPerShare,每股公积金
#esp,每股收益
#bvps,每股净资
#pb,市净率
#timeToMarket,上市日期
#undp,未分利润
#perundp, 每股未分配
#rev,收入同比(%)
#profit,利润同比(%)
#gpr,毛利率(%)
#npr,净利润率(%)
#holders,股东人数

companies <- get_data("companies", USEDB)
#areas <- mongo_stock("areas", host = mongo_remote)
industries <- get_data("industry", USEDB)
concepts <- get_data("concepts", USEDB)

todaydata <- get_data(paste("alltoday_", thedate, sep = ""), USEDB)
todaydata <- todaydata[order(-todaydata$changepercent),]

todaydata <- parse_data_summary(todaydata)
todaytopcount <- parse_today_summary(todaydata)

hc_high <- take_out_companies_high(todaydata, companies)
hc_low <- take_out_companies_low(todaydata, companies)

ccount <- length(todaytopcount$Var1)
cleft <- nrow(todaytopcount[substring(todaytopcount$Var1,0,1) == "-",])
cright <- ccount - cleft - 1
cat("today top count ", ccount, "cleft : ", cleft, ", cright : ", cright, "\n")

ccolor <- c(rep("green", cleft), rep("white", 1), rep("red", cright))

p = ggplot(todaytopcount, aes(x=Var1, y=Freq), group = factor(1)) + 
  geom_bar(stat = "identity", width = 0.99, fill=ccolor) + theme_economist() + 
  geom_text(aes(label=Freq, vjust=-0.8, hjust=0.5, color=Var1), 
            show.legend = FALSE) +
  labs(title=thedate, x="Level", y="Count")

if (export_png) {
  png(filename = paste("alltoday_", thedate, ".png", sep = ""), width = width_1, height = height_1)
  p
}
if (export_png) dev.off()

if (export_png) {
  png(filename = paste("class_", thedate, ".png", sep = ""), width = width_1, height = height_1)
  draw_all(hc_high, hc_low)
}
if (export_png) dev.off()

if (export_png) {
  png(filename = paste("class_hist_", thedate, ".png", sep = ""), width = width_1, height = height_1)
  draw_all_hist(hc_high, hc_low)
}
if (export_png) dev.off()



